package com.fridge.shopping;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.AlertDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.fridge.data.DBHelper;
import com.fridge.data.FridgeItem;
import com.fridge.data.ShoppingItem;
import com.fridge.fridgeList.AddFridgeItemActivity;
import com.fridge.fridgeList.FridgeAdapter;
import com.id2216.fridge.R;

public class ShoppingFragment extends Fragment  {
    private List<ShoppingItem> shoppingItemList; 
    private Button newShoppingItemButton;
    private ShoppingAdapter shoppingAdapter;     
	private DBHelper db;
	private ListView shoppingListView = null;
    
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
        return inflater.inflate(R.layout.shopping_fragment, container, false); 
    } 
       
       
    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
        super.onActivityCreated(savedInstanceState); 

        setHasOptionsMenu(true);
        // New Fridge Button
        newShoppingItemButton = (Button) getActivity().findViewById(R.id.newShoppingItem);
        newShoppingItemButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	
        		Intent addNewItemIntent = new Intent();
        		addNewItemIntent.setClass(getActivity().getBaseContext(), AddShoppingItemActivity.class);
        		getActivity().startActivity(addNewItemIntent);

            }
        });
        
        // setup database
        
        db = new DBHelper(getActivity().getApplicationContext());
        shoppingItemList = db.getAllShoppingItem();
        
        shoppingAdapter = new ShoppingAdapter(getActivity(),
                R.layout.shopping_item_cell, shoppingItemList);
        
        // table
        
        shoppingListView = (ListView) getActivity().findViewById(R.id.shoppingListView); 
        shoppingListView.setAdapter(shoppingAdapter); 
        shoppingListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) 
			{
				CheckBox ch = (CheckBox)view.findViewById(R.id.shoppingCheckBox);

				//Date date = new Date();
				final ShoppingItem item = shoppingItemList.get(position);
				if(ch.isChecked() == true)
				{
	                // Setting Dialog
					AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
					 
	                alertDialog.setTitle("Clear item");	 
	                alertDialog.setMessage("Do you want to remove item from shopping list?");
	 
	                alertDialog.setNeutralButton("MOVE TO FRIDGE", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                    	moveItemToFridge(item);
	                    }
	                });
	 
	                alertDialog.setNegativeButton("YES", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                    	if(db.deleteShoppingItem(item) > 0)
	                    	{
		                    	shoppingItemList.remove(position);
		                    	shoppingAdapter.notifyDataSetChanged();
			                    Toast.makeText(getActivity().getApplicationContext(), "Item removed", Toast.LENGTH_SHORT).show();	                    		
	                    	}
	                    }
	                });
	 
	                alertDialog.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                    	
	                    }
	                });	
	 
	                // Showing Alert Message
	                alertDialog.show();					
				}			
			}        	
        })  ; 
           
    } 
       
//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        inflater.inflate(R.menu.fridge, menu);
//        super.onCreateOptionsMenu(menu,inflater);
//    }
    

    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser == true && shoppingItemList != null) { 
            Runnable run = new Runnable(){
                public void run(){
                    shoppingItemList.clear();
                    List<ShoppingItem> allItem = db.getAllShoppingItem();        
                    shoppingItemList.addAll(allItem);
                    
                    shoppingAdapter.notifyDataSetChanged();        
                }            
           };       
           getActivity().runOnUiThread(run);
        }
    }
    
    
    private void moveItemToFridge(ShoppingItem item )
    {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        DateSetListener dateListener = new DateSetListener(item);
        DatePickerDialog datePicker = new DatePickerDialog(getActivity(), dateListener, year, month, day);
        datePicker.show();

    }
    
//    public void onCheckBoxChanged(int row,int status)
//    {
//    	ShoppingItem item = shoppingItemList.get(row);
//    	item.setStatus(status);
//    	db.updateShoppingItem(item);
//    }

    class DateSetListener implements DatePickerDialog.OnDateSetListener {

    	boolean isAdd = false;
    	ShoppingItem shoppingItem;
    	DateSetListener(ShoppingItem item)
    	{
    		shoppingItem = item;
    	}
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
        	
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, monthOfYear, dayOfMonth);
            Date date = calendar.getTime();

            if( shoppingItem != null)
            {
                db.moveShoppingItemToFridge(shoppingItem, date);
                shoppingItemList.remove(shoppingItem);
                shoppingAdapter.notifyDataSetChanged();
            	shoppingItem = null;
            	
            }
        }
    }


}
